<template>
  <el-drawer v-model="dialogVisible" size="50%" @close="close">
    <template #title>
      <span class="el-drawer__title">{{ title }}</span>
    </template>
    <el-form ref="ruleFormRef" :model="roleForm" :rules="rules" label-width="100px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="权限字符" prop="roleKey">
        <template #label>
          <el-tooltip
            content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"
            placement="top"
          >
            <span class="iconfont icon-wenhao"></span>
          </el-tooltip>
          权限字符
        </template>
        <el-input v-model="roleForm.roleKey" placeholder="请输入权限字符" />
      </el-form-item>
      <el-form-item label="角色顺序" prop="roleSort">
        <el-input-number v-model="roleForm.roleSort" controls-position="right" :min="0" />
      </el-form-item>
      <el-form-item label="角色状态">
        <el-radio-group v-model="roleForm.status">
          <el-radio
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.value"
            >{{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="roleForm.remark" type="textarea" placeholder="请输入内容" />
      </el-form-item>
      <el-form-item label="菜单权限" class="el-checkbox-div" prop="menuIds">
        <div class="el-checkbox-button">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">
            展开/折叠
          </el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">
            全选/全不选
          </el-checkbox>
          <el-checkbox
            v-model="roleForm.menuCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'menu')"
          >
            父子联动
          </el-checkbox>
        </div>
        <el-tree
          ref="menuFormRef"
          class="tree-border"
          :data="menuOptions"
          show-checkbox
          :default-expand-all="false"
          :check-strictly="!roleForm.menuCheckStrictly"
          node-key="id"
          highlight-current
          empty-text="加载中，请稍候..."
          :props="defaultProps"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleClose(ruleFormRef)">确定</el-button>
      </span>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue'
  import { ElMessage, ElTree, FormInstance } from 'element-plus'
  import { reqMenuTreeSelectUrl, reqRoleMenuTreeselect } from '@/api/system/menu'
  import { RoleMenuTreeselect } from '@/api/system/menu/type'
  import { reqRoleAddUrl, reqRoleEditUrl } from '@/api/system/role'
  import { onlyMessageResult } from '@/utils/yixia'

  const ruleFormRef = ref<FormInstance>()
  const dialogVisible = ref(false)
  const title = ref('新增角色')
  const roleForm = reactive({
    roleId: '',
    roleName: '',
    roleKey: '',
    roleSort: '0', // 角色顺序
    menuIds: [] /*所管理菜单*/,
    deptIds: [] /*所管理部门*/,
    menuCheckStrictly: true,
    deptCheckStrictly: true,
    status: '0',
    remark: '',
  })
  let $emit = defineEmits(['getRoleListPage'])
  const defaultProps = {
    children: 'children',
    label: 'label',
    value: 'id',
  }

  function close() {
    ruleFormRef.value.resetFields()
    Object.keys(roleForm).forEach((key) => {
      if (key === 'status' || key === 'roleSort') roleForm[key] = '0'
      else if (key === 'menuIds' || key === 'deptIds') roleForm[key] = []
      else if (key === 'menuCheckStrictly' || key === 'deptCheckStrictly') roleForm[key] = true
      else roleForm[key] = ''
    })
  }

  const show = async (item = {}) => {
    if (!item.roleName) {
      title.value = '新增角色'
      await getMenuTreeselect()
    } else {
      Object.keys(item).forEach((key) => {
        roleForm[key] = item[key]
      })
      title.value = '编辑角色'
      await getRoleMenuTreeselect(item.roleId).then((req: RoleMenuTreeselect) => {
        console.log('req')
        console.log(req)
        roleForm.menuIds = req.checkedKeys
      })
    }
    dialogVisible.value = true
    setTimeout(() => {
      menuFormRef.value!.setCheckedKeys(roleForm.menuIds, false)
    }, 100)
  }

  const rules = reactive({
    roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
    roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
    roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }],
  })

  /*获取选中的节点数据*/
  const getCheckedKeys = () => {
    let checkedKeys = menuFormRef.value!.getCheckedKeys(false)
    let halfCheckedKeys = menuFormRef.value!.getHalfCheckedKeys(true)
    checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    roleForm.menuIds = checkedKeys;
  }

  const handleClose = async (done: () => void) => {
    /*先进行表单验证*/
    if (!ruleFormRef) return
    await ruleFormRef.value!.validate(async (valid: any, fields: any) => {
      if (valid) {
        /*发送异步请求提交数据*/
        try {
          let result = null
          await getCheckedKeys()
          console.log(roleForm);
          if (!roleForm.roleId) {
            /*添加操作*/
            result = await reqRoleAddUrl(roleForm)
            onlyMessageResult(result, '添加成功！', '添加失败!')
          } else {
            /*修改操作*/
            result = await reqRoleEditUrl(roleForm)
            onlyMessageResult(result, '修改成功！', '修改失败!')
          }
          /*关闭对话框*/
          if(result.code === 200) {
            dialogVisible.value = false
            $emit('getRoleListPage')
          }
        } catch (e) {}
      } else {
        ElMessage({
          type: 'error',
          message: 'error submit!' + fields,
        })
      }
    })
  }

  const menuOptions = ref([]) // 菜单树选项
  const deptOptions = ref([]) // 菜单树选项
  const menuExpand = ref(false) /*折叠*/
  const menuNodeAll = ref(false) /*全选/全不选*/
  const menuFormRef = ref<InstanceType<typeof ElTree>>()

  // 树权限（展开/折叠）
  const handleCheckedTreeExpand = (value: boolean, type: string) => {
    if (type == 'menu') {
      let treeList = menuOptions.value
      /*遍历值*/
      for (let i = 0; i < treeList.length; i++) {
        menuFormRef.value!.store!.nodesMap[treeList[i]['id']].expanded = value
      }
    } else if (type == 'dept') {
      let treeList = deptOptions.value
      for (let i = 0; i < treeList.length; i++) {
        //this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
      }
    }
  }

  // 树权限（全选/全不选）
  const handleCheckedTreeNodeAll = (value: boolean, type: string) => {
    if (type == 'menu') {
      /*将menuOptions中所有的节点都选中*/
      menuFormRef.value!.setCheckedNodes(value ? menuOptions.value : ([] as Node[]), false)
    } else if (type == 'dept') {
      //this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
    }
  }

  // 树权限（父子联动）
  const handleCheckedTreeConnect = (value: boolean, type: string) => {
    if (type == 'menu') {
      roleForm.menuCheckStrictly = value ? true : false
    } else if (type == 'dept') {
      roleForm.deptCheckStrictly = value ? true : false
    }
  }

  /** 根据角色ID查询菜单树结构 */
  const getRoleMenuTreeselect = (roleId: any) => {
    return reqRoleMenuTreeselect(roleId).then((response: any) => {
      menuOptions.value = response.menus
      return response
    })
  }
  /** 查询菜单树结构 */
  const getMenuTreeselect = async () => {
    await reqMenuTreeSelectUrl().then((response) => {
      menuOptions.value = response.data
    })
  }

  defineExpose({
    show,
  })
</script>

<script lang="ts">
  export default {
    dicts: ['sys_normal_disable'],
  }
</script>

<style lang="scss" scoped>
  @import '../index';
</style>
